package com.atstudent.gmall.common.config;/*
 * @author: XueYouPeng
 * @time: 23.9.11 下午 2:25
 */

import com.atstudent.gmall.common.properties.ThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableConfigurationProperties(value = ThreadPoolProperties.class)
public class ThreadPoolExcutorConfiguration {

    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    @Value("${spring.application.name}")
    private String applicationName;


    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                threadPoolProperties.getCorePoolSize(),//核心线程数
                threadPoolProperties.getMaximumPoolSize(), //最大线程数
                threadPoolProperties.getKeepAliveTime(), //存活时间
                TimeUnit.SECONDS, //时间单位 秒
                //new一个阻塞队列
                new ArrayBlockingQueue<>(threadPoolProperties.getWorkQueueSize()),
                //new一个线程工厂
                new ThreadFactory() {
                    int count = 0;

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("[pool-" + applicationName + "-" + count + "]");
                        count++;
                        return thread;
                    }
                },
                //拒绝策略
                new ThreadPoolExecutor.AbortPolicy()
        );
        return threadPoolExecutor;
    }
}
